package com.engine.salary.util.page;

import com.engine.salary.annotation.TableTitle;
import lombok.Data;
import lombok.ToString;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

@Data
@ToString
public class PageInfo<T> extends com.engine.salary.component.PageInfo<T> {
    Class<T> clazz;

    public void setColumns(List<Column> columns) {
        this.columns.addAll(columns);
    }

    public void clearAndSetColumns(List<Column> columns) {
        this.columns.clear();
        this.columns.addAll(columns);
    }

    List<Column> columns = new ArrayList<>();
    List<DataSource> dataSource = new ArrayList<>();

    public PageInfo() {
    }

    public PageInfo(Class<T> clazz) {
        this.clazz = clazz;
        this.columns = buildColumns();
    }

    public PageInfo(List<T> list) {
        super(list);
    }

    public PageInfo(List<T> list, Class<T> clazz) {
        super(list);
        this.clazz = clazz;
        this.columns = buildColumns();
    }


    public List<Column> buildColumns() {
        if(clazz==null){
            return this.columns;
        }
        Field[] fields = clazz.getDeclaredFields();
        for (Field f : fields) {
            boolean isanno = f.isAnnotationPresent(TableTitle.class);
            if (isanno) {
                TableTitle annotation = f.getAnnotation(TableTitle.class);
                String title = annotation.title();
                String dataIndex = annotation.dataIndex();
                String key = annotation.key();
                boolean display = annotation.display();
                Column column = Column.builder().title(title).dataIndex(dataIndex).key(key).display(display).build();
                columns.add(column);
            }
        }
        return columns;
    }
}
